package com.jzo2o.customer.controller.consumer;

import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.model.Result;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wjh
 * @create 2024-04-22 14:12
 */
@Api(tags = "用户端 - 地址簿接口")
@RestController("consumerAddressBookController")
@RequestMapping("/consumer/address-book")
public class AddressBookController {
    
    @Resource
    private IAddressBookService addressBookService;
    
    @ApiOperation("添加地址")
    @PostMapping
    public Result add(@RequestBody @Validated AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        return addressBookService.add(addressBookUpsertReqDTO);
    }
    
    @GetMapping("/page")
    public PageResult<AddressBookResDTO> pageQuery(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        return addressBookService.pageQuery(addressBookPageQueryReqDTO);
    }
    
    @GetMapping("/{id}")
    public AddressBookResDTO getAddressBook(@PathVariable("id") Long id) {
        return addressBookService.getAddressBookById(id);
    }
    
    @PutMapping("/{id}")
    public Result updateAddressBook(@PathVariable("id") Long id, @RequestBody @Validated AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        return addressBookService.updateAddressBookById(id, addressBookUpsertReqDTO);
    }
    
    @DeleteMapping("/batch")
    public Result batchDelete(@RequestBody List<String> ids) {
        List<Long> idList = ids.stream().map(Long::parseLong).collect(Collectors.toList());
        boolean b = addressBookService.removeByIds(idList);
        return b ? Result.ok() : Result.error("删除失败");
    }
    
    @PutMapping("/default")
    public Result setDefault(@RequestParam("id") Long id, @RequestParam("flag") Integer flag) {
        return addressBookService.setDefault(id,flag);
    }
    
    @GetMapping("/defaultAddress")
    public AddressBookResDTO getDefaultAddress() {
        AddressBook defaultAddress = addressBookService.getDefaultAddress();
        if (defaultAddress != null) {
            return BeanUtils.toBean(defaultAddress, AddressBookResDTO.class);
        }
        return null;
    }
}
